import { h } from 'vue'
import { defineStore } from 'pinia'
import { message } from 'ant-design-vue'
import { cloneDeep } from 'lodash-es'
import { router } from '@/routes'
import { post } from '@/utils/request'
import systemLoading from '@/utils/loading'
import MenuTopLayout from '@/layouts/MenuTopLayout.vue'
import { getSystemConfig } from '@/utils/systemConfig'
import MenuLeftLayout from '@/layouts/MenuLeftLayout.vue'
import useUserStore from './user'

const allRouters = import.meta.glob('../views/**/index.vue')
let buttonAuthority = {}
export default defineStore('app', {
  persist: true, // 持久化
  state: () => {
    return {
      IS_PRINT: true,
      MENU_OPEN: true,
      LAST_MENU_ID: '',
      ORG_CODE: '', // 组织编码
      ORG_LIST: '', // 组织列表
      CURRENT_ROUTE_NAME: '', // 动态添加路由的name
      CURRENT_ROUTE_PATH: '', // 动态添加路由的path
      BUTTON_AUTHORITY: {}, // 按钮权限
      ROUTER_AUTHORITY: [], //路由权限
      reportRoute: [],
      keepAliveRouters: []
    }
  },
  actions: {
    async login(data, redirect = '', isJump = true) {
      const userStore = useUserStore()
      userStore.isLogin = true
      userStore.empId = data.id
      userStore.empName = data.username
      userStore.ksmc = data.ksmc
      userStore.ksdm = data.ksdm
      this.getOrgList(data.id)
      await this.getRole(data.id)
      isJump && router.push({ path: redirect || '/' })
    },
    async loginOut(isFetch = true) {
      const userStore = useUserStore()

      router.push({ path: '/login' })
      localStorage.setItem('systemConfig', '{}')
      userStore.$reset()
      this.$reset()
      sessionStorage.removeItem('systemConfigRefreshing')
      buttonAuthority = {}
      if (isFetch) {
        const { code, msg } = await post('/login/logout', { empId: userStore.empId, empName: userStore.empName, lastMenuId: this.LAST_MENU_ID })
        if (code !== 0) return message.error(msg || '退出失败')
      }
      // message.success('退出成功')
    },
    async getRole(empId) {
      systemLoading(true)
      const { code, data = [], msg } = await post('/common/emp/getSystemDeptList', { empId })
      if (code !== 0) return message.error(msg || '获取权限失败')
      this.ROUTER_AUTHORITY = generateMenu(data)
      this.BUTTON_AUTHORITY = buttonAuthority
      systemLoading(false)
    },
    async getOrgList(empId) {
      const { code, data = [], msg } = await post('/common/emp/getOrganizationListByEmpId', { empId })
      if (code !== 0) return message.error(msg || '获取组织机构失败')
      this.ORG_LIST = data || []
    },
    addRouter(isGoToFirst = false, isTargetBlank = false) {
      const menuList = this.ROUTER_AUTHORITY.filter((item) => item.label === this.CURRENT_ROUTE_NAME)
      const routeList = generateRouter(cloneDeep(menuList))
      if (routeList.length === 0) return
      return new Promise((resolve) => {
        try {
          // 获取第一个菜单
          const [firstMenuItem] = routeList[0]?.children || []
          const firstMenuPath = firstMenuItem?.type === '菜单' ? firstMenuItem.path : firstMenuItem?.children[0]?.path
          router.addRoute(routeList[0])
          resolve(true)
          if (isGoToFirst && firstMenuPath) {
            if (isTargetBlank) {
              window.open(firstMenuPath)
            } else {
              if (firstMenuItem.label) {
                document.title = getSystemConfig('HISNAME') + ' - ' + firstMenuItem.label
              }
              router.push({ path: firstMenuPath })
            }
          }
        } catch (error) {
          // console.error('路由写入失败，请检查配置!', error)
        }
      })
    }
  }
})
//menuType 1:模块 2:目录 3:菜单 4:按钮

const generateMenu = (data = []) => {
  return data.map((item) => {
    const menu = {
      label: item.menuName, //名称
      path: item.routeUrl,
      key: item.routeUrl,
      id: item.id,
      menuIcon: item.menuIcon,
      isTargetBlank: item.isTargetBlank === '1', //新页面打开
      ...(item.showStatus === 0 && { isHide: item.showStatus === 0 }), //隐藏菜单
      ...(item.menuIcon && { menuIcon: item.menuIcon }), //图标
      ...(item.isUrl === 1 && { isUrl: true }), //外链
      groupName: { 1: '门诊', 2: '住院', 3: '视光', 4: '辅助', 5: '战救' }[item.groupCode || '1'], //分组
      type: { 1: '模块', 2: '目录', 3: '菜单', 4: '按钮' }[item.menuType]
    }
    if (item.children?.length) {
      if (item.menuType === 3) {
        //按钮权限单独存储
        buttonAuthority[item.routeUrl] = [...(buttonAuthority[item.routeUrl] || []), ...(item.children?.map((item) => item.menuName) || [])]
      } else {
        menu.children = generateMenu(item.children)
      }
    }
    return menu
  })
}
const generateRouter = (data = []) => {
  return data.map((item) => {
    if (item.type === '模块') {
      item.component = ['报表中心'].includes(item.label) ? MenuLeftLayout : MenuTopLayout
    }
    if (item.type === '菜单') {
      item.component = getComponent(item.path.split('?')[0])
    }
    if (item.children?.length) {
      item.children = generateRouter(item.children)
    }
    return item
  })
}
const getComponent = (name) => {
  const currentComponent = allRouters[`../views${name}/index.vue`]
  if (!currentComponent) {
    message.error(`未知的组件 ${name} 请确认组件路径是否正确`)
    return h('div', { style: 'height: 100%; width: 100%; background-color: #f0f2f5;' }, '请确认页面是否正确')
  }
  return currentComponent
}
